<template>
  <div>
    <a-space direction="vertical">
      <a-space>
        <a-select v-model:value="hostSelect.grps" showSearch :placeholder="$t('osManager.selectGroup')" @change="fnClickGroup"
                  style="width: 280px"
        >
          <a-select-option
            v-for="grp in groups"
            :key="grp.host_group_id"
            :value="grp.host_group_id"
          >
            {{ grp.host_group_name }}
          </a-select-option>
          <a-select-option label="default" value="other"></a-select-option>
        </a-select>
        <a-select v-model:value="hostSelect.hosts"  mode="tags" :placeholder="$t('osManager.selectHost')" @change="fnClickHost"
                  style="width: 280px">
          <a-select-option value="all" @click="fnClickAllOrNot" style="margin-left: 20px; border: 1px dashed">
            {{ hostSelect.isSelectAll ? $t('osManager.cancelAllSelect') : $t('osManager.allSelect') }}
          </a-select-option>

          <a-select-option
            v-for="node in selectNodes"
            :key="node.host_id"
            :label="node.host_name + '(' + node.host_ip + ')'"
            :value="node.host_id"
          >
            {{ node.host_name + '(' + node.host_ip + ')' }}
          </a-select-option>
        </a-select>
      </a-space>

    <a-table style="width: 560px" :columns="column" :data-source="showHostList" tooltip-effect="dark" height="200">
      <template #bodyCell="{ record, column }">
        <template v-if="column.dataIndex === 'group'">
          <span>{{ record.grpLabel.length ? record.grpLabel.join(',') : '--' }} </span>
        </template>
        <template v-else-if="column.dataIndex === 'hostLabel'">
          <span>{{ record[column.dataIndex] }}</span>
        </template>
        <template v-if="column.dataIndex === 'operation'">
          <a-button class="actionBtn" :icon="h(DeleteOutlined)" @click="fnDeleteHost(record.id)"></a-button>
        </template>
      </template>
    </a-table>
    </a-space>
  </div>
</template>

<script>
import { api } from '@/api'
import { h } from 'vue'
import { DeleteOutlined } from '@ant-design/icons-vue'

export default {
  emits: ['change', 'hadRefresh'],
  name: 'hostChoose',
  props: ['refresh'],
  data() {
    return {
      column: [
        {
          key: 'group',
          title: this.$t('osManager.hostGroup'),
          dataIndex: 'group',
        },
        {
          key: 'hostLabel',
          title: this.$t('osManager.host'),
          dataIndex: 'hostLabel',
        },
        {
          key: 'operation',
          title: this.$t('common.operation'),
          dataIndex: 'operation',
        },
      ],
      showHostList: [], // 去重后的选中主机的详细列表
      hostSelect: {
        grps: '',
        hosts: [],
        isSelectAll: false,
      },
      selectNodes: [],
      selectHostId: [],
      groups: [],
      nodes: [],
    }
  },
  created() {
    this.initPage()
  },
  watch: {
    refresh(val) {
      if (val) {
        this.fnReset()
        this.$emit('hadRefresh')
      }
    },
  },
  methods: {
    DeleteOutlined, h,
    async initPage() {
      const [_, grpRes] = await api.getHostGroups()
      if (grpRes) {
        this.groups = grpRes.host_group_infos
      }
      const [, res] = await api.getHosts({
        host_group_list: [],
      })
      this.nodes = res.host_infos
      this.fnReset()
    },
    fnReset() {
      this.hostSelect = {
        grps: '',
        hosts: [],
        isSelectAll: false,
      }
      this.selectHostId = []
      this.showHostList = []
      this.selectNodes = this.nodes
    },
    fnChange() {
      this.$emit('change', this.fnGetHostParam())
    },
    fnGetHostParam() {
      return this.showHostList.map(item => item.host_id)
    },
    fnClickGroup() {
      if (this.hostSelect.grps === 'other') {
        // 显示没有组的主机
        this.selectNodes = this.nodes.filter(item => item.host_group.length === 0)
        this.fnUpdateNodeCheck()
        return
      }
      const group = this.groups.filter(item => item.host_group_id === this.hostSelect.grps)[0]
      this.selectNodes = this.nodes.filter(item => item.host_group_name === group.host_group_name)
      this.fnUpdateNodeCheck()
    },
    fnClickHost(value) {
      console.log(value)
      const group = this.groups.filter(item => item.host_group_id === this.hostSelect.grps)[0]
      this.selectNodes.forEach(item => {
        if (value.indexOf(item.host_id) > -1) {
          // 被选中
          this.fnHandleHostList(item, group)
          return
        }
        if (this.selectHostId.indexOf(item.host_id) > -1) {
          this.fnUncheckHost(item.host_id)
        }
      })
      this.hostSelect.isSelectAll = this.selectNodes.length === value.length
      this.fnChange()
    },
    fnClickAllOrNot() {
      this.hostSelect.isSelectAll = !this.hostSelect.isSelectAll
      if (this.hostSelect.isSelectAll) {
        // 选中全选
        const group = this.groups.filter(item => item.host_group_id === this.hostSelect.grps)[0]
        this.selectNodes.forEach(item => {
          if (this.hostSelect.hosts.indexOf(item.host_id) === -1) {
            this.hostSelect.hosts.push(item.host_id)
          }
          this.fnHandleHostList(item, group)
        })
        this.fnChange()
        return
      }
      this.hostSelect.hosts = []
      this.selectNodes.forEach(item => {
        this.fnUncheckHost(item.host_id)
      })
      this.fnChange()
    },
    fnHandleHostList(item, group) {
      // 处理展示的去重主机列表
      if (this.selectHostId.indexOf(item.host_id) === -1) {
        // 不在列表中,则直接push
        this.selectHostId.push(item.host_id)
        const newHost = {
          id: item.host_id,
          host_id: item.host_id,
          grpId: this.hostSelect.grps,
          hostLabel: `${item.host_name}(${item.host_ip})`,
          grpLabel: group ? [group.host_group_name] : [],
          grpIdList: group ? [group.host_group_id] : [],
        }
        this.showHostList.push(newHost)
        return
      }

      // 该主机已经被选中过了，更新组名称
      const selectHost = this.showHostList.filter(host => host.host_id === item.host_id)[0]
      if (group && selectHost.grpIdList.indexOf(group.host_group_id) === -1) {
        selectHost.grpIdList.push(group.host_group_id)
        selectHost.grpLabel.push(group.host_group_name)
      }
    },
    fnDeleteHost(id) {
      this.fnUncheckHost(id)
      this.fnUpdateNodeCheck()
      this.fnChange()
    },
    fnUncheckHost(id) {
      // 取消选中，在showHostList和hostsId中移除
      const index = this.selectHostId.indexOf(id)
      this.selectHostId.splice(index, 1)
      this.showHostList.splice(index, 1)
    },
    fnUpdateNodeCheck() {
      // 更新主机选中状态
      this.hostSelect.hosts = []
      this.selectNodes.forEach(item => {
        if (this.selectHostId.indexOf(item.host_id) > -1) {
          this.hostSelect.hosts.push(item.host_id)
        }
      })
    },
  },
}
</script>

<style scoped></style>
